<template>
  <el-dialog :close-on-click-modal="false" v-model="state.dialogVisible" :title="title" width="40%">
    <el-form :model='state.formData' label-width='130px' class='dialogForm'>
      <el-upload class='upload-demo' :limit="1" drag :accept='accept' :file-list='state.fileList' :show-file-list='true'
        :on-success='fileUploadEnd' :action='fileUploadUrl()'>
        <i class='el-icon-upload'></i>
        <div class='el-upload__text'>将文件拖到此处，或<em>点击上传</em></div>
        <div class='el-upload__tip'>请选择({{  accept  }})文件</div>
      </el-upload>

      <div>
        <el-form-item>
          <el-button type='primary' @click='submit'>导入</el-button>
          <el-button @click='cancel'>取消</el-button>
        </el-form-item>
      </div>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" >
import { defineComponent, reactive, onMounted } from "vue";
import { ElMessage } from 'element-plus'
import axios from "axios"

export default defineComponent({
  emits: [
    'childClick'
  ],
  props: {
    title: String,
    accept: String
  },
  setup(props, context) {
    const state = reactive({
      dialogVisible: false,
      fileList: [],
      formData: { filePath: '' },
      fileresponse: ""
    });
    onMounted(() => {
      console.log(state.dialogVisible);
    });
    const childMethod = () => {
      console.log("子组件的事件被触发了")
      state.dialogVisible = true;
    }
    const fileUploadEnd = (response, file) => {
      state.fileresponse = file.name;
      state.formData.filePath = response[0];
      if (state.fileList.length > 0) {
        state.fileList.splice(0, 1);
      }
    }
    const cancel = () => {
      state.dialogVisible = false;
    }
    const submit = () => {
      if (state.formData.filePath == '') {
        ElMessage.error('请选择上传的文件')
        return;
      }
      context.emit('childClick', state.formData)
    }
    const fileUploadUrl = () => {
      return axios.defaults.baseURL+'File';
    }
    return {
      state,
      childMethod,
      fileUploadEnd,
      cancel,
      submit,
      fileUploadUrl
    };
  }
})
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>